<template>
  <PageWrapper>
    <n-grid cols="1 s:1 m:1 l:3 xl:3 2xl:3" responsive="screen" :x-gap="12">
      <n-gi span="1" class="mb-4">
        <n-card title="字典类型" :segmented="{ content: 'hard' }" :bordered="false" size="small">
          <template #header-extra>
            <n-input-group style="width: 100%">
              <n-input
                clearable
                :style="{ width: '80%' }"
                v-model:value="leftParams.dict_name"
                @keyup.enter="leftReloadTable"
                placeholder="请输入字典名称"
              />
              <n-button type="primary" @click="leftReloadTable">
                <template #icon>
                  <n-icon>
                    <SearchOutlined />
                  </n-icon>
                </template>
                查询
              </n-button>
            </n-input-group>
          </template>
          <BasicTable
            :columns="leftColumns"
            :request="leftLoadDataTable"
            :row-key="(row) => row.dictId"
            ref="leftTableRef"
            :actionColumn="leftActionColumn"
            @update:checked-row-keys="onCheckedRow"
          >
            <template #tableTitle>
              <n-space>
                <n-button type="primary" @click="openAddDictType">
                  <template #icon>
                    <n-icon>
                      <FileAddOutlined />
                    </n-icon>
                  </template>
                  添加
                </n-button>
              </n-space>
            </template>
          </BasicTable>
        </n-card>
      </n-gi>
      <n-gi span="2">
        <n-card :bordered="false" class="mb-4 proCard">
          <BasicTable
            :columns="rightColumn"
            :request="loadDataTable"
            :row-key="(row) => row.dictCode"
            ref="rightTableRef"
            :actionColumn="actionColumn"
          >
            <template #tableTitle>
              <n-space>
                <n-input-group style="width: 100%">
                  <n-input
                    clearable
                    :style="{ width: '80%' }"
                    v-model:value="rightParams.dict_label"
                    @keyup.enter="rightReloadTable"
                    placeholder="请输入字典名称"
                  />
                  <n-button type="primary" @click="rightReloadTable">
                    <template #icon>
                      <n-icon>
                        <SearchOutlined />
                      </n-icon>
                    </template>
                    查询
                  </n-button>
                </n-input-group>
                <n-button type="primary" @click="openAddDictData">
                  <template #icon>
                    <n-icon>
                      <FileAddOutlined />
                    </n-icon>
                  </template>
                  添加
                </n-button>
              </n-space>
            </template>
          </BasicTable>
        </n-card>
      </n-gi>
    </n-grid>
    <!-- 添加/编辑 字典 -->
    <AddDictType ref="addDictTypeRef" :title="addDictTypeTitle" @change="leftReloadTable()" />
    <!-- 添加/编辑 字典项 -->
    <AddDictData ref="addDictDataRef" :title="addDictDataTitle" @change="rightReloadTable()" />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref, reactive, h, onMounted, nextTick, unref } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { dictTypeList, dictDataList, delDictType, delDictData } from '@/api/system/dictionary';
  import AddDictType from './components/AddDictType.vue';
  import AddDictData from './components/AddDictData.vue';
  import { useMessage, NCheckbox, NTag } from 'naive-ui';
  import { FileAddOutlined, SearchOutlined } from '@vicons/antd';

  const message = useMessage();
  const leftTableRef = ref();
  const rightTableRef = ref();
  const dictTableList = ref<any[]>([]);
  const rowKeys = ref<any[]>([]);
  const rowKeysName = ref('');
  const isEdit = ref(false);
  const dictTypeTableList = ref();
  const dictType = ref('sys_user_sex');
  const addDictTypeRef = ref();
  const addDictDataRef = ref();
  const addDictTypeTitle = ref('添加字典');
  const addDictDataTitle = ref('添加字典项');

  const leftParams = ref({
    dict_name: '',
  });

  const rightParams = ref({
    dict_label: '',
  });

  const leftColumns = [
    {
      fixed: 'left',
      width: 60,
      render(row) {
        return h(NCheckbox, {
          checked: dictType.value === row.dict_type,
          'onUpdate:checked'() {
            dictType.value = row.dict_type;
            rightTableRef.value.reload();
          },
        });
      },
    },
    {
      title: '字典名称',
      key: 'dict_name',
    },
    {
      title: '字典类型',
      key: 'dict_type',
    },
  ];

  const leftActionColumn = reactive({
    width: 140,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
      return h(TableAction as any, {
        actions: [
          {
            label: '删除',
            onPositiveClick: removeDictType.bind(null, record),
            isConfirm: true,
            confirmContent: `您确定要删除【${record.dict_name}】吗？`,
            positiveText: '确定',
          },
          {
            label: '编辑',
            onClick: editDictType.bind(null, record),
          },
        ],
      });
    },
  });

  const rightColumn = [
    {
      title: '字典项名称',
      key: 'dict_label',
    },
    {
      title: '字典项值',
      key: 'dict_value',
    },
    {
      title: '排序',
      key: 'dict_sort',
    },
    {
      title: '状态',
      key: 'status',
      render(row) {
        return h(
          NTag,
          {
            type: row.status === '0' ? 'success' : 'error',
          },
          {
            default: () => (row.status === '0' ? '正常' : '停用'),
          },
        );
      },
    },
    {
      title: '创建时间',
      key: 'created_at',
    },
  ];

  const actionColumn = reactive({
    width: 140,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
      return h(TableAction as any, {
        actions: [
          {
            label: '删除',
            onPositiveClick: removeDictData.bind(null, record),
            isConfirm: true,
            confirmContent: `您确定要删除【${record.dict_label}】吗？`,
            positiveText: '确定',
          },
          {
            label: '编辑',
            onClick: editDictData.bind(null, record),
          },
        ],
      });
    },
  });

  //添加字典类型
  function openAddDictType() {
    addDictTypeRef.value.openModal();
    nextTick(() => {
      isEdit.value = false;
      addDictTypeRef.value.setProps({ title: '添加字典类型' });
    });
  }

  //删除字典类型
  function removeDictType(record) {
    rowKeysName.value = record.dict_name;
    delDictType({ dict_id: record.dict_id }).then(() => {
      message.success('删除成功');
      leftReloadTable();
    });
  }

  //编辑字段类型
  function editDictType(record) {
    addDictTypeRef.value.openModal();
    nextTick(() => {
      isEdit.value = true;
      addDictTypeRef.value.setProps({ title: '编辑字典类型' });
      addDictTypeRef.value.setFieldsValue({
        ...unref(record),
      });
    });
  }

  //删除字典
  function removeDictData(record) {
    rowKeysName.value = record.dict_name;
    delDictData({ dict_code: record.dict_code }).then(() => {
      message.success('删除成功');
      rightReloadTable();
    });
  }

  //添加字典项
  function openAddDictData() {
    addDictDataRef.value.openModal();
    nextTick(() => {
      isEdit.value = false;
      addDictDataRef.value.setProps({ title: '添加字典项' });
      addDictDataRef.value.setFieldsValue({
        dict_type: dictType.value,
      });
    });
  }

  //编辑字典
  function editDictData(record) {
    addDictDataRef.value.openModal();
    nextTick(() => {
      isEdit.value = true;
      addDictDataRef.value.setProps({ title: '编辑字典项' });
      addDictDataRef.value.setFieldsValue({
        ...unref(record),
      });
    });
  }

  //选择字典项
  function onCheckedRow(keys) {
    rowKeys.value = keys;
  }

  //刷新字典类型
  function leftReloadTable() {
    leftTableRef.value.restReload();
  }

  //刷新字典列表
  function rightReloadTable() {
    rightTableRef.value.restReload();
  }

  //加载字典项列表
  const leftLoadDataTable = async (res) => {
    const result = await dictTypeList({ ...leftParams.value, ...res });
    dictTypeTableList.value = result.list;
    if (result.list.length) {
      dictType.value = result.list[0].dict_type;
    }
    return result;
  };

  //加载字典项值列表
  const loadDataTable = async (res) => {
    const result = await dictDataList({ dict_type: dictType.value, ...rightParams.value, ...res });
    dictTableList.value = result.list;
    return result;
  };

  onMounted(() => {});
</script>

<style lang="less" setup></style>
